import {createAsyncThunk, createSlice, PayloadAction} from "@reduxjs/toolkit";

import {MenuTreeData} from "type/SecurityMenu";
import {requestGet} from "util/request";
import LogFactory from "log/LogFactory";
import {ReduxStatus} from "enum/ReduxStatus";

const log = LogFactory.getLog("navigateReducer") ;
export type NavigateState = {
    loading: boolean ,
    /**
     * 0: 初始状态
     * 1: 正在加载
     * 2: 加载失败
     * 3: 加载成功
     * 4: 刷新
     * 8: 数据加载成功,准备菜单渲染,可以设置菜单树的Icon图标,但是加载菜单之后不可以再修改菜单树的数据,设置状态为3
     */
    status: ReduxStatus ,
    menuTreeData: MenuTreeData[]
} ;

const initialState: NavigateState = {
    loading: true,
    status: ReduxStatus.INIT ,
    menuTreeData: [] ,
} ;


export const fetchMenuTreeData = createAsyncThunk(
    'navigate/fetchMenuTreeData',
    async () => {
        const response = await requestGet<MenuTreeData[]>("/manager/security-user-menu/nav/tree") ;
        if (response.code !== 200){
            log.error("请求服务器加载菜单数据失败",response) ;
            return null ;
        }
        return response.data ;
    }
) ;

export const navigateReducer = createSlice({
    name: 'navigate',
    initialState,
    reducers: {
        /**
         * 更新状态数值
         * @param state
         * @param action
         */
        updateStatus: (state, action: PayloadAction<0|1|2|3|4|8>) => {
            state.status = action.payload ;
        }
    },
    extraReducers: (builder) => {
        builder.addCase(fetchMenuTreeData.pending, (state) => {
            state.loading = true ;
            state.status = ReduxStatus.PENDING ;
        }) ;
        builder.addCase(fetchMenuTreeData.fulfilled, (state, action) => {
           // log.requestDebug("请求返回的菜单树数据",action.payload) ;
            if (action.payload === null){
                state.status = ReduxStatus.FAILED ;
                state.loading = false ;
                return ;
            }
            state.menuTreeData = action.payload ;
            state.status = ReduxStatus.SUCCESS ;
            state.loading = false ;
        }) ;
    }
}) ;

export const {updateStatus} = navigateReducer.actions ;
export default navigateReducer.reducer ;

